/** biome-ignore-all lint/suspicious/noExplicitAny: off */
import type { Middleware } from '../context/types';

// 性能监控中间件，用于记录更新时间
export const performanceMiddleware: Middleware = (key, value, next) => {
  const startTime = performance.now();

  // 调用下一个中间件
  next(value);

  const endTime = performance.now();
  const duration = endTime - startTime;

  // 只有当更新时间超过10ms时才记录，避免过多日志
  if (duration > 10) {
    console.log(`Context update for ${key} took ${duration.toFixed(2)}ms`);
  }
};

// 性能监控中间件，用于记录更新频率
export const rateLimitMiddleware: Middleware = (key, value, next) => {
  // 存储每个key的最后更新时间
  const lastUpdateTimes = (globalThis as any).__contextLastUpdateTimes || {};
  (globalThis as any).__contextLastUpdateTimes = lastUpdateTimes;

  const now = Date.now();
  const lastUpdateTime = lastUpdateTimes[key] || 0;
  const minInterval = 100; // 最小更新间隔，单位ms

  if (now - lastUpdateTime >= minInterval) {
    lastUpdateTimes[key] = now;
    next(value);
  } else {
    // 如果更新过于频繁，延迟执行
    setTimeout(
      () => {
        next(value);
      },
      minInterval - (now - lastUpdateTime),
    );
  }
};

// 性能监控中间件，用于记录订阅者数量
export const subscriptionCountMiddleware: Middleware = (_key, value, next) => {
  // 先调用下一个中间件
  next(value);

  // 这里可以添加逻辑来记录订阅者数量
  // 例如，将订阅者数量发送到监控系统
};
